package com.chenchao.reflection;

import java.lang.reflect.Constructor;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/21 19:55
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.javareflection.Test02.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 获取构造器对象
 */
public class Test02 {
    public static void main(String[] args) throws Exception {
        //获取字节码对象
        Class c=Class.forName("com.chenchao.reflection.Fish.java");

        //获取构造方法
            //获取无参公共构造器
        Constructor constructor = c.getConstructor();
        System.out.println(constructor);


            //获取有参公共构造器,传入参数的字节码对象
        Constructor constructor1 = c.getConstructor(String.class);
        System.out.println(constructor1);
            //获取所有公共构造器
        Constructor[] constructors = c.getConstructors();
        for (Constructor constructor2 : constructors) {
            System.out.println(constructor);
        }
            //获取私有构造器,注意int就是int不要写成Integer
        Constructor declaredConstructor = c.getDeclaredConstructor(int.class);
            //打印构造函数名
        System.out.println(declaredConstructor.getName());

        //使用构造器创建对象(只能用公共方法)
        Fish fish  =(Fish) constructor1.newInstance("小黑鱼");
        System.out.println(fish);
    }
}
